<template>
  <div>
    <!--  数据操作栏  -->
    <div style="margin-bottom: 20px;">
      <el-button
        type="primary"
        :disabled="selection.length < 1"
        @click="handlePurchaseBatch"
      >{{$t('product_purchase_cmpts_biztable_126')}}</el-button>
      <el-button
        v-hasRole="['admin','purchaser']"
        type="success"
        @click="handleExportAll"
      >{{$t('product_purchase_cmpts_biztable_127')}}</el-button>
    </div>
    <!--  数据表格  -->
    <div class="table-container">
      <el-table
        ref="dataTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        border
        :cell-style="{textAlign: 'center'}"
        :header-cell-style="{textAlign: 'center'}"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column
          prop="productSn"
          :label="$t('product_purchase_cmpts_biztable_128')"
          width="120"
        />
        <el-table-column
          prop="productName"
          :label="$t('product_purchase_cmpts_biztable_129')"
          width="120"
          show-overflow-tooltip
        />
        <el-table-column
          :label="$t('product_purchase_cmpts_biztable_130')"
        >
          <template v-slot="scope">
            <el-image
              :src="scope.row.imageUrl"
              fit="contain"
              style="height: 80px;"
            />
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('product_purchase_cmpts_biztable_131')"
          show-overflow-tooltip
        >
          <template v-slot="scope">
            <div>{{ scope.row.categories.join(' / ') }}</div>
          </template>
        </el-table-column>
        <el-table-column :label="$t('product_purchase_cmpts_biztable_132')">
          <template v-slot="scope">
            <!--suppress JSValidateTypes -->
            <el-tag :type="scope.row.status === productStatus.ON ? 'success' : 'danger'">
              {{ scope.row.status === productStatus.ON ? $t('product_purchase_cmpts_biztable_133') : $t('product_purchase_cmpts_biztable_134') }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="color"
          :label="$t('product_purchase_cmpts_biztable_135')"
        />
        <el-table-column
          prop="size"
          :label="$t('product_purchase_cmpts_biztable_136')"
        />
        <el-table-column
          prop="stock"
          :label="$t('product_purchase_cmpts_biztable_137')"
          width="100"
        />
        <el-table-column :label="$t('product_purchase_cmpts_biztable_138')">
          <template v-slot="scope">
            <el-button
              size="medium"
              type="primary"
              plain
              @click="handlePurchase(scope.row)"
            >{{$t('product_purchase_cmpts_biztable_139')}}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 15px;">
        <el-pagination
          :current-page="pageRecord.current"
          :page-sizes="pageRecord.pageSizeList"
          :page-size="pageRecord.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageRecord.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <!--单个采购表格-->
    <el-dialog
      :title="$t('product_purchase_cmpts_biztable_139')"
      :visible.sync="oneVisible"
      width="400px"
    >
      <el-form
        ref="purchaseForm"
        :model="purchaseData"
        label-width="80px"
        size="small"
      >
        <el-form-item :label="$t('product_purchase_cmpts_biztable_128')">
          <div>{{ purchaseData.productSn }}</div>
        </el-form-item>
        <el-form-item :label="$t('product_purchase_cmpts_biztable_129')">
          <div>{{ purchaseData.productName }}</div>
        </el-form-item>
        <el-form-item :label="$t('product_purchase_cmpts_biztable_135')">
          <div>{{ purchaseData.color }}</div>
        </el-form-item>
        <el-form-item :label="$t('product_purchase_cmpts_biztable_136')">
          <div>{{ purchaseData.size }}</div>
        </el-form-item>
        <!--cake: 需要指定prop，rules才会生效-->
        <el-form-item
          :label="$t('product_purchase_cmpts_biztable_140')"
          prop="quantity"
          :rules="[{required: true, type: 'number', min: 1, message: $t('product_purchase_cmpts_biztable_141'), trigger: 'change'}]"
        >
          <el-input
            v-model.number="purchaseData.quantity"
            type="number"
            min="1"
          />
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="handleCloseOneDlg">{{$t('product_purchase_cmpts_biztable_142')}}</el-button>
        <el-button
          type="primary"
          @click="doPurchaseOne"
        >{{$t('product_purchase_cmpts_biztable_143')}}</el-button>
      </div>
    </el-dialog>
    <!--批量采购表格-->
    <el-dialog
      :title="$t('product_purchase_cmpts_biztable_126')"
      :visible.sync="batchVisible"
    >
      <el-table
        :data="purchaseBatchData"
        tooltip-effect="dark"
        style="width: 100%"
        border
        :cell-style="{textAlign: 'center'}"
        :header-cell-style="{textAlign: 'center'}"
      >
        <el-table-column
          type="index"
          width="55"
        />
        <el-table-column
          prop="productSn"
          :label="$t('product_purchase_cmpts_biztable_128')"
          width="120"
        />
        <el-table-column
          prop="productName"
          :label="$t('product_purchase_cmpts_biztable_129')"
          width="120"
          show-overflow-tooltip
        />
        <el-table-column
          prop="color"
          :label="$t('product_purchase_cmpts_biztable_135')"
        />
        <el-table-column
          prop="size"
          :label="$t('product_purchase_cmpts_biztable_136')"
        />
        <el-table-column :label="$t('product_purchase_cmpts_biztable_140')">
          <template v-slot="scope">
            <el-input
              v-model.number="scope.row.quantity"
              type="number"
              min="1"
            />
          </template>
        </el-table-column>
        <el-table-column :label="$t('product_purchase_cmpts_biztable_138')">
          <template v-slot="scope">
            <el-button
              size="small"
              plain
              @click="removePurchaseData(scope.$index)"
            >{{$t('product_purchase_cmpts_biztable_144')}}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="handleCloseBatchDlg">{{$t('product_purchase_cmpts_biztable_142')}}</el-button>
        <el-button
          type="primary"
          @click="doPurchaseBatch"
        >{{$t('product_purchase_cmpts_biztable_143')}}</el-button>
      </template>
    </el-dialog>
    <!--采购单-->
    <el-dialog
      :title="$t('product_purchase_cmpts_biztable_145')"
      :visible.sync="receiptVisible"
    >
      <ReceiptForm :receipt-data="receiptData" />
    </el-dialog>
  </div>
</template>

<script>
import * as productStatus from '@/constants/product'
import { purchaseBatch, purchaseOne } from '@/api/purchase'
import { exportStock } from '@/api/excel'
import ReceiptForm from '@/views/product/purchase/cmpts/ReceiptForm.vue'

export default {
  name: 'BizTable',
  components: { ReceiptForm },
  props: {
    tableData: {
      type: Array,
      required: true
    },
    pageRecord: {
      type: Object,
      required: true
    },
    handleSizeChange: {
      type: Function,
      required: true
    },
    handleCurrentChange: {
      type: Function,
      required: true
    },
    handleRefresh: {
      type: Function,
      required: true
    }
  },
  data() {
    return {
      selection: [],
      oneVisible: false,
      purchaseData: {
        productSn: "",
        productName: "",
        color: "",
        size: "",
        quantity: 1,
      },
      batchVisible: false,
      purchaseBatchData: [],
      receiptData: {},
      receiptVisible: false,
    }
  },
  computed: {
    productStatus() {
      return productStatus
    },
  },
  methods: {
    _transform2PurchaseData(item) {
      const data = {...this.purchaseData}
      Object.keys(data).forEach(key => {item[key] && (data[key] = item[key])})
      return data;
    },
    handleSelectionChange(selection) {
      this.selection = selection;
    },
    handlePurchase(row) {
      this.purchaseData = this._transform2PurchaseData(row);
      this.oneVisible = true
    },
    handleCloseOneDlg() {
      this.oneVisible = false;
      Object
        .keys(this.purchaseData)
        .forEach(key =>
        {this.purchaseData[key] = (key !== 'quantity' ? "" : 1)})
    },
    doPurchaseOne() {
      this.$refs.purchaseForm.validate(isValid => {
        if (!isValid) {
          this.$message.warning(this.$t('product_purchase_cmpts_biztable_146'));
          return;
        }
        purchaseOne(this.purchaseData).then(res => {
          this.receiptData = res.data;
          this.$message.success(this.$t('product_purchase_cmpts_biztable_147'))
          this.closeDlg()
        })
      })
    },
    handlePurchaseBatch() {
      this.purchaseBatchData = this.selection.map(this._transform2PurchaseData)
      this.batchVisible = true
    },
    removePurchaseData(index) {
      if (this.purchaseBatchData.length <= 1) {
        this.$message.warning(this.$t('product_purchase_cmpts_biztable_148'));
        return;
      }
      this.purchaseBatchData.splice(index, 1);
    },
    handleCloseBatchDlg() {
      this.batchVisible = false;
      this.purchaseBatchData = [];
      this.$refs.dataTable.clearSelection();
    },
    doPurchaseBatch() {
      // 检查数量输入正确
      for (let data of this.purchaseBatchData) {
        if (!data.quantity || data.quantity < 1) {
          this.$message.warning(this.$t('product_purchase_cmpts_biztable_149'))
          return;
        }
      }
      purchaseBatch(this.purchaseBatchData).then(res => {
        this.receiptData = res.data;
        this.$message.success(this.$t('product_purchase_cmpts_biztable_147'));
        this.closeDlg(true)
      })
    },
    closeDlg(isBatch = false) {
      if (isBatch) {
        this.handleCloseBatchDlg()
      } else {
        this.handleCloseOneDlg()
      }
      this.handleRefresh();
      this.showReceipt();
    },
    showReceipt() {
      this.receiptVisible = true;
    },
    async handleExportAll(){
      await exportStock().then((res) => {
          // console.log(res);
          const a = document.createElement("a"); // 创建一个新的 a 标签
          const url = window.URL.createObjectURL(res); // 创建一个 URL 对象，表示 Blob 对象的内容
          a.href = url;// 将 a 标签的 href 设置为 URL 对象
          a.download = this.$t('product_purchase_cmpts_biztable_150'); // 设置文件名
          document.body.appendChild(a);// 触发点击事件
          a.click();
          // 清理
          window.URL.revokeObjectURL(url);
          document.body.removeChild(a);
        })
        .catch((e) => {
          // console.log(e);
        });
    },
  },
}
</script>

<style lang="scss" scoped>

</style>
